﻿using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace KINLO.DRV.Drv
{
    public class HTNElectronicBalanceSocketDrv
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HTNElectronicBalanceSocketDrv));
        int PerReadDataLen = 20;
        string IpAddr;
        int Port;
        Socket socket;
        public HTNElectronicBalanceSocketDrv(string ip, int port, int dataLen = 20)
        {
            try
            {
                this.IpAddr = ip;
                this.Port = port;
                this.PerReadDataLen = dataLen;
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ReceiveTimeout = 3000;
                SendTimeout = 3000;
                socket.ReceiveTimeout = ReceiveTimeout;
                socket.SendTimeout = SendTimeout;
            }
            catch (Exception ex)
            {
                log.Error(string.Format("创建电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex));
                Messenger.Default.Send(string.Format("创建电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex), "ReceiveEventInfo");
            }
        }
        public bool Connected
        {
            get { return socket.Connected; }
        }
        public void Open()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(IpAddr, Port);
                log.Info(string.Format("打开电子称 {0},{1}", IpAddr, Port));
            }
            catch (Exception ex)
            {
                log.Error(string.Format("打开电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex));
                Messenger.Default.Send(string.Format("打开电子称 {0},{1} 发生异常 ：", IpAddr, Port, ex), "ReceiveEventInfo");
            }
        }
        public void Disconnect()
        {
            if (!socket.Connected)
                return;
            socket.Close();

            log.Info(string.Format("关闭电子称 {0},{1}", IpAddr, Port));
        }

        public int FindCRIndex(byte[] bytes)
        {             
            var sign= Encoding.Default.GetBytes("\n")[0];
            for (var i = bytes.Length-1; i> 0; i--)
            {
                if (bytes[i] == sign)
                    return i;
            }
            return -1;
        }

        Random rnd = new Random();
        public byte[] Read()
        {
            try
            {
                var buff = new byte[4096];
                var len = socket.Receive(buff);
                var buff1= buff.Take(len).ToArray();
                var index=FindCRIndex(buff1);
                var result= buff1.Skip(index - 19).Take(20).ToArray();
                //var rst1 = Encoding.Default.GetString(result);
                //log.Info(string.Format("电子称读:{0} {1} {2}", IpAddr, Port, rst1)); 
                return result;
            }
            catch (Exception ex)
            {
                log.Error(string.Format("电子称 {0},{1} 读发生异常：{2}", IpAddr, Port, ex));
                Messenger.Default.Send(string.Format("电子称 {0},{1} 发生异常：{2}", IpAddr, Port, ex), "ReceiveEventInfo");
                //6.5
                Open();
                return null;
            }
        }
        public void ClearZero()
        {
            try
            {
                log.Info(string.Format(" 电子称:{0}:{1} 清零开始", IpAddr, Port));
                Socket socket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket1.ReceiveTimeout = ReceiveTimeout;
                socket1.SendTimeout = SendTimeout;
                socket1.Connect(IpAddr, Port);
                var b = Encoding.Default.GetBytes("DZ\r\n");
                socket1.Send(b);
                socket1.Close();
                log.Info(string.Format(" 电子称:{0}:{1} 清零完成", IpAddr, Port));
            }
            catch (Exception ex)
            {
                log.Info(string.Format("电子称:{0},{1} 清零时发生异常:{2}", IpAddr, Port, ex));
                Messenger.Default.Send(string.Format("电子称:{0},{1} 清零时发生异常:{2}", IpAddr, Port, ex), "ReceiveEventInfo");
            }
        }

        int receiveTimeout;
        public int ReceiveTimeout
        {
            get { return receiveTimeout; }
            set
            {
                receiveTimeout = value;
            }
        }
        int sendTimeout;
        public int SendTimeout
        {
            get { return sendTimeout; }
            set
            {
                sendTimeout = value;
            }
        }
    }
}
